package hydrap2p.modulemanager.listen;

import java.util.LinkedList;
import java.util.List;

import hydrap2p.modulemanager.ModuleController;
import hydrap2p.modulemanager.ModuleInfo;

public class Listeners{

	private static List<Listener> listeners = new LinkedList<Listener>();
	public static ModuleController controller = null;
	
	public static void addListener(Listener listener)
	{
		synchronized(listeners)
		{
			if (!listeners.contains(listener))
			{
				ListenerQueue temp=new ListenerQueue(listener);
				listeners.add(temp);
				syncListener(temp);
			}
			
		}
	}
	public static void delListener(Listener listener)
	{
		synchronized(listeners)
		{
			listeners.remove(listener);
		}
		listener.stop();
	}
	
	private static void syncListener(Listener listener)
	{
		for (ModuleInfo info : controller.getAllModules())
		{
				try {
					listener.addModule(info);
				} catch (Exception e) {
					// Invalid listener
					delListener(listener);
					break;
				}
		}
	}
	
	public static void addModule(ModuleInfo module) {
		synchronized(listeners)
		{
			for (Listener listener : listeners)
			{
				try {
					listener.addModule(module);
				} catch (Exception e) {
					delListener(listener);
				}
			}
		}
	}

	public static void updateModule(ModuleInfo module) {
		synchronized(listeners)
		{
			for (Listener listener : listeners)
			{
				try {
					listener.updateModule(module);
				} catch (Exception e) {
					delListener(listener);
				}
			}
		}
	}

	public static void delModule(ModuleInfo module) {
		synchronized(listeners)
		{
			for (Listener listener : listeners)
			{
				try {
					listener.delModule(module);
				} catch (Exception e) {
					delListener(listener);
				}
			}
		}
	}
	public static void shutdown() {
		synchronized(listeners)
		{
			for (Listener listener : listeners)
			{
				listener.stop();
			}
			listeners.clear();
		}
	}

}
